import * as vscode from 'vscode';
import * as os from 'os';
import RemoteContainer from './remote-container';
import User from './user';
import * as utils from './utils'

export default class DSHome {
  private context: vscode.ExtensionContext;
  private remoteContainer: RemoteContainer;
  private user: User;
  private devstarHomePageUrl: string;
  private devstarDomain: string | undefined

  constructor(context: vscode.ExtensionContext, user: User) {
    this.context = context;
    this.user = user;
    this.remoteContainer = new RemoteContainer(user);

    this.devstarDomain = utils.devstarDomain()
    if (undefined == this.devstarDomain || "" == this.devstarDomain) {
      this.devstarHomePageUrl = "https://devstar.cn/devstar-home"
    } else {
      this.devstarHomePageUrl = this.devstarDomain.endsWith('/') ? this.devstarDomain + "devstar-home" : this.devstarDomain + "/devstar-home"
    }
  }

  async toggle(devstarHomePageUrl: string = this.devstarHomePageUrl) {
    const panel = vscode.window.createWebviewPanel(
      'homeWebview',
      vscode.l10n.t('Home'),
      vscode.ViewColumn.One,
      {
        enableScripts: true,
        retainContextWhenHidden: true,
      }
    );

    panel.webview.html = await this.getWebviewContent(devstarHomePageUrl);

    panel.webview.onDidReceiveMessage(
      async (message) => {
        const data = message.data
        const need_return = message.need_return
        if (need_return) {
          // ================= need return ====================
          switch (message.command) {
            // ----------------- frequent -----------------------
            case 'getHomeConfig':
              const config = {
                language: vscode.env.language
              }
              panel.webview.postMessage({command: 'getHomeConfig', data: {homeConfig: config}})
              break;
            case 'getUserToken':
              const userToken = this.user.getUserTokenFromLocal()
              if (userToken === undefined) {
                panel.webview.postMessage({ command: 'getUserToken', data: { userToken: '' } })
                break;
              } else {
                panel.webview.postMessage({ command: 'getUserToken', data: { userToken: userToken } })
                break;
              }
            case 'getUsername':
              const username = this.user.getUsernameFromLocal()
              if (username === undefined) {
                panel.webview.postMessage({ command: 'getUsername', data: { username: '' } })
                break;
              } else {
                panel.webview.postMessage({ command: 'getUsername', data: { username: username } })
                break;
              }
            case 'firstOpenRemoteFolder':
              // data.host - project name
              await this.remoteContainer.firstOpenProject(data.host, data.hostname, data.port, data.username, data.path, this.context)
              break;
            case 'openRemoteFolder':
              this.remoteContainer.openRemoteFolder(data.host, data.port, data.username, data.path);
              break;
            case 'getDevstarDomain':
              panel.webview.postMessage({ command: 'getDevstarDomain', data: { devstarDomain: this.devstarDomain } })
              break;
            // ----------------- not frequent -----------------------
            case 'setUserToken':
              this.user.setUserTokenToLocal(data.userToken)
              if (data.userToken === this.user.getUserTokenFromLocal()) {
                panel.webview.postMessage({ command: 'setUserToken', data: { ok: true } })
                break;
              } else {
                panel.webview.postMessage({ command: 'setUserToken', data: { ok: false } })
                break;
              }
            case 'setUsername':
              this.user.setUsernameToLocal(data.username);
              if (data.username === this.user.getUsernameFromLocal()) {
                panel.webview.postMessage({ command: 'setUsername', data: { ok: true } });
                break;
              } else {
                panel.webview.postMessage({ command: 'setUsername', data: { ok: false } });
                break;
              }
            case 'getUserPublicKey':
              var userPublicKey = '';
              if (this.user.existUserPrivateKey()) {
                userPublicKey = this.user.getUserPublicKey();
                panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } })
                break;
              } else {
                panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } })
                break;
              }
            case 'createUserPublicKey':
              await this.user.createUserSSHKey();
              if (this.user.existUserPublicKey()) {
                panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: true } })
                break;
              } else {
                panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: false } })
                break;
              }
            case 'getMachineName':
              const machineName = os.hostname();
              panel.webview.postMessage({ command: 'getMachineName', data: { machineName: machineName } })
          }
        } else {
          // ================= don't need return ==============
          // frequent
          switch (message.command) {
            // ----------------- frequent -----------------------
            case 'showInformationNotification':
              vscode.window.showInformationMessage(data.message);
              break;
            case 'showWarningNotification':
              vscode.window.showWarningMessage(data.message)
              break;
            case 'showErrorNotification':
              await utils.showErrorNotification(data.message)
              break;
          }
        }
      },
      undefined,
      this.context.subscriptions
    );

    this.context.subscriptions.push(panel)
  }


  async getWebviewContent(devstarHomePageUrl: string): Promise<string> {
    return `
      <?php
      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
      header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
      header("Allow: GET, POST, OPTIONS, PUT, DELETE");
      ?>
      <!DOCTYPE html>
      <html lang="en">

      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>DevStar Home</title>
      </head>

      <body>
        <iframe id="embedded-devstar" src="${devstarHomePageUrl}" sandbox="allow-popups allow-same-origin allow-scripts allow-forms allow-top-navigation-by-user-activation" width="100%" height="100%" frameborder="0"
          style="border: 0; left: 0; right: 0; bottom: 0; top: 0; position:absolute;">
        </iframe>

        <script>
          const vscode = acquireVsCodeApi();

          function firstOpenRemoteFolder() {
            vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path });
          }

          function openRemoteFolder() {
            vscode.postMessage({ command: 'openRemoteFolder', host: host, path: path });
          }

          function firstOpenRemoteFolderWithData(host, username, password, port, path) {
            vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path });
          }

          function openRemoteFolderWithData(host, path) {
            vscode.postMessage({ command: 'openRemoteFolder', host: host, path: path });
          }


          async function communicateVSCode(command, data) {
            return new Promise((resolve, reject) => {
              // request to vscode 
              vscode.postMessage({ command: command, need_return: true, data: data })

              function handleResponse(event) {
                const jsonData = event.data;
                if (jsonData.command === command) {
                  // console.log("communicateVSCode", jsonData.data)

                  // return vscode response
                  window.removeEventListener('message', handleResponse) // 清理监听器
                  resolve(jsonData.data)
                }
              }

              window.addEventListener('message', handleResponse)

              setTimeout(() => {
                window.removeEventListener('message', handleResponse)
                reject('timeout')
              }, 5000); // 5秒超时
            })
          }

          // 监听子页面的消息
          window.addEventListener('message', async (event) => {
            // 出于安全考虑，检查 event.origin 是否是你预期的源
            // if (event.origin !== "http://expected-origin.com") {
            //     return;
            // }
            try {
              const jsonData = event.data;

              if (jsonData.target === 'vscode') {
                const actionFromHome = jsonData.action
                const dataFromHome = jsonData.data
                const dataFromVSCodeResponse = await communicateVSCode(actionFromHome, dataFromHome)

                var iframe = document.getElementById('embedded-devstar');
                if (iframe && iframe.contentWindow) {
                  iframe.contentWindow.postMessage({ action: actionFromHome, data: dataFromVSCodeResponse }, '*')
                }
              } else if (jsonData.target === 'vscode_no_return') {
                vscode.postMessage({ command: jsonData.action, need_return: false, data: jsonData.data })
              }
            } catch (error) {
              console.error('Error parsing message:', error);
            }
          });
        </script>
      </body>

      </html>`
  }
}
